package com.thinkit.bigdata.web.controller.bus;

import com.thinkit.bigdata.core.ConfigHelper;
import com.thinkit.bigdata.core.util.TaskUtil;
import com.thinkit.bigdata.core.util.es.ESUtil;
import com.thinkit.bigdata.web.coremet.SystemStatic;
import com.thinkit.bigdata.web.model.es.audioEs.Source;
import com.thinkit.bigdata.web.model.es.audioEs.WorkScores;
import org.apache.log4j.Logger;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;

import java.util.ArrayList;
import java.util.List;

/**
 * 质检任务异步修改任务名称
 */
public class PerTaskThread implements Runnable {

    private static Logger logger = Logger.getLogger(PerTaskThread.class);

    private long id;
    private String workName;
    private ESUtil esUtil;

    public PerTaskThread(long id, String workName, ESUtil esUtil) {
        this.id = id;
        this.workName = workName;
        this.esUtil = esUtil;
    }

    @Override
    public void run() {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.must(QueryBuilders.nestedQuery("workScores", QueryBuilders.matchQuery("workScores.workId", id), ScoreMode.None));
        try {
            logger.info("质检任务异步修改任务名称");
            //todo 用jscript指定字段查询优化
            List<Source> sources = new ArrayList<>();
            //总条数
            Integer sum = SystemStatic.crud.queryQBuilderAllByMes(SystemStatic.AUDIO_ES_INDEX, SystemStatic.AUDIO_ES_TYPE, boolQuery);
            //单词查询条数
            int excleMax = ConfigHelper.getInt("export.data.sheet.max.number", 1000);
            List<Integer> pageTout = TaskUtil.formatSum(sum, excleMax);//todo最后一个数字需要特殊处理:6022
            for (Integer aPageTout : pageTout) {
                List<String> docList = SystemStatic.crud.queryMapQBuilderList(
                        SystemStatic.AUDIO_ES_INDEX,
                        SystemStatic.AUDIO_ES_TYPE,
                        aPageTout,
                        excleMax,
                        boolQuery,
                        "",
                        ""
                );
                if (docList.isEmpty())
                    continue;
                sources.addAll(esUtil.strs2Entitys(docList));
            }
            for (Source source : sources) {
                for (WorkScores work : source.getWorkScores()) {
                    if (work.getWorkId() == id) {
                        work.setWorkName(workName);
                    }
                }
            }
            //todo 有时间可以用script局部更新优化
            esUtil.updateSources(sources);
        } catch (Exception e) {
            //TODO 修改任务名称异常情况暂不考虑 后续完善
            e.printStackTrace();
        }
    }
}
